将Map集合的键值对按照指定字符串拼接后输出
使用StringJoiner类使用StringBuffer类Guava包提供的Joiner类总结
使用StringJoiner类
Map map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
StringJoiner sj = new StringJoiner(",");
map.forEach((key, value) -> sj.add(key + ":" + value));
String result = sj.toString();
System.out.println(result); // key1:value1,key2:value2,key3:value3
使用StringBuffer类
Map map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
StringBuffer sb = new StringBuffer();
for (Map.Entry entry : map.entrySet()) {
sb.append(entry.getKey()).append(":").append(entry.getValue()).append(",");
}
String result = sb.toString();
// 去掉最后一个逗号
if (result.endsWith(",")) {
result = result.substring(0, result.length() - 1);
}
System.out.println(result); // key1:value1,key2:value2,key3:value3
Guava包提供的Joiner类
Map map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
String result = Joiner.on(",").withKeyValueSeparator(":").join(map);
System.out.println(result); // key1:value1,key2:value2,key3:value3
总结
一般情况下,效率最高的方法应该是使用StringJoiner类来实现,因为它是在Java 8中引入的,使用了较新的底层技术来提高拼接字符串的效率,而且代码简洁易懂。
其次,使用Guava包的Joiner类也是一个很好的选择,虽然相对于StringJoiner类来说效率略低一些,但是其提供了更多的拼接选项,可以更方便地实现复杂的字符串拼接操作。
最后,使用StringBuffer类来实现的效率相对较低,因为它是一个线程安全的类,每次执行拼接操作都需要进行同步,而且代码也较为冗长。但是如果需要进行线程安全的字符串拼接操作,StringBuffer仍然是一个不错的选择。
|